# Sequelize的笔记
# 关联 include
// 建立关联
Profile.belongsTo(User)
User.findAndCountAll({
include: [
{ model: Profile, where: { active: true } attributes:[]}
],
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
嵌套关联
include: [{
model: DB.note,
include:[
{
model: DB.user,
attributes: ['id', 'name', 'avatar']
}
]
}]
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 属性 attributes
排除属性
attributes: { exclude: ['password'] }
1
# 插件:sequelize-auto
https://github.com/sequelize/sequelize-auto
安装
npm i sequelize-auto -D
1
sequelize-auto.js
const SequelizeAuto = require('sequelize-auto')
const { host, user, password, database, dialect, port } = require('...')
const options = {
host,
dialect,
directory: './models', // 指定输出 models 文件的目录
port,
additional: {
timestamps: false
}
}
const auto = new SequelizeAuto(database, user, password, options)
auto.run(err => {
if (err) throw err
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package.json
添加启动项 npm run models
"scripts": {
"models": "node sequelize-auto.js"
}
1
2
3
2
3
引用 util/DB.js
const Sequelize = require('sequelize')
const initModels = require('../models/init-models')
const { host, user, password, database, dialect } = require('...')
const sequelize = new Sequelize(database, user, password, { host, dialect, define: { timestamps: false } })
module.exports = initModels(sequelize)
1
2
3
4
5
6
2
3
4
5
6
使用
const DB = require('../utils/DB')
const userInfo = await DB.User.findOne({ isDelete: 0 })
1
2
2
另,命令行方式 package.json
"scripts": {
"model": "sequelize-auto -l ts -h localhost -d redbook -u root -x 123456 -p 3306 --dialect mysql -o server/model"
},
1
2
3
2
3